<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Course_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    function get_all_courses(){
        
	$query = $this->db->query('SELECT id, course_name FROM courses');

	foreach ($query->result() as $row)
	    $tab_courses[] = array('id' => $row->id, 'course_name' => $row->course_name);

	return $tab_courses;
    }

    function get_courses_by_module($module_id){
        
	$query = $this->db->query('SELECT id, course_name, module FROM courses WHERE module='.$module_id);

	foreach ($query->result() as $row)
	    $tab_courses_by_module[] = array('id' => $row->id, 'course_name' => $row->course_name);

	return $tab_courses_by_module;
    }

    function get_course_name($course_id){
        
	$query = $this->db->query('SELECT course_name FROM courses WHERE id='.$course_id);

	foreach ($query->result() as $row)
	    return $row->course_name;
    }

    function get_teacher_firstname($course_id){
        
	$query = $this->db->query('SELECT up.firstname
	       	 			  FROM users u, user_profiles up, teachers t, courses c
	       	 			  WHERE u.id=up.user_id and u.id=t.id and c.teacher_id=t.id and c.id='.$course_id);

	foreach ($query->result() as $row)
	    return $row->firstname;
    }

    function get_teacher_lastname($course_id){
        
	$query = $this->db->query('SELECT up.lastname
	       	 			  FROM users u, user_profiles up, teachers t, courses c
	       	 			  WHERE u.id=up.user_id and u.id=t.id and c.teacher_id=t.id and c.id='.$course_id);

	foreach ($query->result() as $row)
	    return $row->lastname;
    }

    function add_course($teacher_id, $course_name, $module_id){

    	$data = array(
          'course_name' => $course_name,
          'teacher_id' => $teacher_id,
          'module_id' => $module_id
        );

	$this->db->insert('courses', $data); 

	if($this->db->affected_rows() > 0)
	    return 'Vous venez d'ajouter un cours';
    }

    function delete_course($teacher_id, $course_id){

    	$query = $this->db->query('SELECT c.id FROM teachers t, courses c
	       	 			  WHERE c.teacher_id=t.id and t.id='.$teacher_id.' and c.id='.$course_id);

	foreach ($query->result() as $row)
	    $result = 1;

	if(!empty($result)){	
            $query = 'DELETE FROM courses WHERE id='.$course_id;
	    $this->db->query($query);

	    $query = 'DELETE FROM course_supports WHERE course_id='.$course_id;
	    $this->db->query($query);

	    if($this->db->affected_rows() > 0)
	        return 'Vous venez de supprimer un cours';
	}
    }
}